package models;

import java.util.*;
import javax.persistence.*;

import play.data.format.*;
import play.data.validation.*;

public class TicketForm {

	@Constraints.Required
	@Formats.NonEmpty
	public String session;

	@Constraints.Required
	@Formats.NonEmpty
	public String seat;

	@Constraints.Required
	@Formats.NonEmpty
	public String lang;

	public HashMap<String, List<String>> convert(String seatList) {
		String[] seat = seatList.split(",");
		HashMap<String, List<String>> temp =  new HashMap<String, List<String>>();

		for(int i=0; i<seat.length; i++) {
			String[] tSeat = seat[i].split(":");
			List<String> seats = temp.get(tSeat[0]);
			if(seats == null) {
				seats = new ArrayList<String>();
			}
			seats.add(tSeat[1]);
			temp.put(tSeat[0], seats);
		}

		return temp;
	}

	public boolean isSold(String id, String seat) {
		HashMap<String, List<String>> temp = convert(seat);
		String[] sessions = id.substring(1).split(":");

		for(int i=0;i<sessions.length;i++){
			List<String> seats = temp.get(sessions[i]);
			if(seats != null) {
				for(int j=0;j<seats.size();j++){
					if(Payment.isTicketSold(Long.parseLong(sessions[i]), seats.get(j))){
						return true;
					}
				}
			}
		}

		return false;
	}

	public boolean isHold(String id, String seat) {
		HashMap<String, List<String>> temp = convert(seat);
		String[] sessions = id.substring(1).split(":");

		for(int i=0;i<sessions.length;i++){
			List<String> seats = temp.get(sessions[i]);
			if(seats != null) {
				List<OnHold> records = OnHold.findBySession(Long.parseLong(sessions[i]));
				for(OnHold record : records){
					if(Arrays.asList(seats.toArray()).contains(record.seat_no)){
						return true;
					}
				}
			}
		}

		return false;
	}

	public String validate() {
		if(isSold(session, seat)){
			return "The seat(s) is/are sold in the selected session.";
		}

		if(isHold(session, seat)){
			return "The seat(s) is/are hold in the selected session.";
		}

		return null;
	}


}

